package com.zjlanyun.eplus;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;

import com.aihook.alertview.library.AlertView;
import com.aihook.progressview.library.ProgressViewDialog;
import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.utils.KeyboardUtils;
import com.blankj.utilcode.utils.ToastUtils;
import com.yanzhenjie.nohttp.rest.Response;
import com.zjlanyun.eplus.greendao.DBHelper;
import com.zjlanyun.eplus.greendao.IrModelAccess;
import com.zjlanyun.eplus.network.WebApi;
import com.zjlanyun.eplus.nohttp.HttpRequest;
import com.zjlanyun.eplus.nohttp.SimpleHttpListener;
import com.zjlanyun.eplus.utils.SPData;
import com.zjlanyun.eplus.utils.UpdateManager;
import com.zjlanyun.eplus.view.BaseActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.Bind;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class Login extends BaseActivity {

    @Bind(R.id.btn_login) Button btn_login;
    @Bind(R.id.et_username) EditText et_username;
    @Bind(R.id.et_password) EditText et_password;
    @Bind(R.id.et_customer_number) EditText et_customer_number;
    @Bind(R.id.ib_menu) ImageButton ib_menu;

    private String username, password, customer_number, FEmpNO, FNumber;
    private long user_id;
    private String[] menuTitles = {"连接设置", "解除绑定", "离线绑定", "检查更新", "更新配置"};
    private ProgressViewDialog mProgressViewDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        initBaseView();
        initView();
    }

    // 初始化view
    private void initView() {
        title.setText(R.string.login);
        ib_menu.setVisibility(View.VISIBLE);

        if (!SPData.getUserinfo().getString("username", "").equals("")) {
            et_username.setText(SPData.getUserinfo().getString("username", ""));
        }
        if (!SPData.getUserinfo().getString("customer_number", "").equals("")) {
            et_customer_number.setText(SPData.getUserinfo().getString("customer_number", ""));
        }

        // 登录
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                username = et_username.getText().toString();
                password = et_password.getText().toString();
                customer_number = et_customer_number.getText().toString();

                if (customer_number.equals("")) {
                    ToastUtils.showShortToast(R.string.input_customer_number);
                } else if (username.equals("")) {
                    ToastUtils.showShortToast(R.string.input_username);
                } else {
                    login();
                }
            }
        });

        //菜单
        //"连接设置", "解除绑定", "离线绑定", "检查更新", "更新配置"
        ib_menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                KeyboardUtils.hideSoftInput(mActivity);
                new AlertView(null, null, "取消", menuTitles, null, mContext, AlertView.Style.ActionSheet, new com.aihook.alertview.library.OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        if (position == 0) {
                            Intent intent = new Intent(mContext, ConnectSetup.class);
                            intent.putExtra("from", Login.class.getName());
                            startActivity(intent);
                        } else if (position == 1) {
                            unbind();
                        } else if (position == 2) {
                            bindOffline();
                        } else if (position == 3) {
                            new UpdateManager(mContext).manualCheckUpdate();
                        } else if (position == 4) {
                            updateSetting();
                        }
                    }
                }).show();
            }
        });
    }

    /**
     * 更新配置
     */
    private void updateSetting() {
        mProgressViewDialog = new ProgressViewDialog(mContext);
        mProgressViewDialog.showWithMaskType(ProgressViewDialog.ProgressViewDialogMaskType.None);
        final ConnectSetup connectSetup = new ConnectSetup();
        HttpRequest client = new HttpRequest(mContext, WebApi.api(), false);
        client.getRequest().add("action", "connectConfig");
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, final Response<JSONObject> response) {
                super.onSucceed(what, response);
                Observable.create(new Observable.OnSubscribe<String>() {
                    @Override
                    public void call(Subscriber<? super String> subscriber) {
                        connectSetup.updateSetting(response.get(), mContext);
                        subscriber.onCompleted();
                    }
                }).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {
//                        new ConnectSetup().updateSetting(response.get(), mContext);
                        mProgressViewDialog.dismiss();
                        ToastUtils.showShortToast("更新成功");
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(String s) {

                    }
                });
            }

            @Override
            public void onFailed(int what, Response<JSONObject> response) {
                super.onFailed(what, response);
                mProgressViewDialog.dismiss();
            }
        });
    }

    /**
     * 设备解绑
     */
    private void unbind() {
        new AlertView("提示", "确定解除绑定当前设备吗？", "取消", new String[]{"解除绑定"}, null, mContext, AlertView.Style.AlertDialog, new com.aihook.alertview.library.OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == 0) {
                    Common.deviceUnbind(mContext);
                }
            }
        }).show();
    }

    /**
     * 绑定设备
     */
    private void bind() {
        HttpRequest client = new HttpRequest(mContext, SPData.getConfig().getString("device_bind_url", ""));
        client.getRequest().add("device_token", SPData.getUserinfo().getString("device_token", ""));
        client.getRequest().add("customer_number", customer_number);
        client.getRequest().add("erp_username", username);
        client.getRequest().add("device_type", "android");
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                super.onSucceed(what, response);
                SPData.getUserinfo().putString("customer_number", customer_number);
                SPData.getUserinfo().putBoolean("isBind", true);
                loginSuccess();
            }
        });
    }

    /**
     * 离线绑定
     */
    private void bindOffline() {
        customer_number = et_customer_number.getText().toString().trim();
        if (TextUtils.isEmpty(customer_number)) {
            ToastUtils.showShortToast(R.string.input_customer_number);
            return;
        }
        HttpRequest client = new HttpRequest(mContext, SPData.getConfig().getString("device_bind_url", ""));
        client.getRequest().add("device_token", SPData.getUserinfo().getString("device_token", ""));
        client.getRequest().add("customer_number", customer_number);
        client.getRequest().add("erp_username", et_username.getText().toString().trim());
        client.getRequest().add("device_type", "android");
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                super.onSucceed(what, response);
                SPData.getUserinfo().putString("customer_number", customer_number);
                SPData.getUserinfo().putBoolean("isBind", true);
                ToastUtils.showShortToast(R.string.bind_success);
            }
        });
    }

    /**
     * 登录ERP
     */
    private void login() {
        HttpRequest client = new HttpRequest(mContext, WebApi.api());
        client.getRequest().add("action", "login");
        client.getRequest().add("username", username);
        client.getRequest().add("password", password);
        client.getRequest().add("usertype", Data.USER_TYPE_INTERIOR);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                super.onSucceed(what, response);
                JSONObject data = response.get().optJSONObject("data");
                FEmpNO = data.optString("FEmpNO");
                FNumber = data.optString("FNumber");
                user_id = data.optLong("id");

                //保存用户的访问权限
                try {
                    DBHelper.getDaoSession(mContext).getIrModelAccessDao().deleteAll();
                    JSONArray ir_model_access = response.get().getJSONObject("data").getJSONArray("ir_model_access");
                    ArrayList<IrModelAccess> irModelAccessArrayList = new ArrayList<>(JSON.parseArray(ir_model_access.toString(), IrModelAccess.class));
                    for (int i = 0; i < irModelAccessArrayList.size(); i++) {
                        DBHelper.getDaoSession(mContext).getIrModelAccessDao().insertOrReplace(irModelAccessArrayList.get(i));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                //判断是否已经绑定
                if (SPData.getUserinfo().getBoolean("isBind", false)) {
                    loginSuccess();
                } else {
                    bind();
                }
            }
        });
    }

    //登录成功后处理
    private void loginSuccess(){
        SPData.getUserinfo().putString("username", username);
        SPData.getUserinfo().putString("password", password);
        SPData.getUserinfo().putBoolean("isLogin", true);
        SPData.getUserinfo().putInt("usertype", Data.USER_TYPE_INTERIOR);
        SPData.getUserinfo().putString("FEmpNO", FEmpNO);
        SPData.getUserinfo().putString("FNumber", FNumber);
        SPData.getUserinfo().putLong("user_id", user_id);

        //企业内部
        startActivity(new Intent(mContext, MenuActivity.class));
        Home.mActivity.finish();
        finish();
    }
}
